package com.hxzy.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.hxzy.common.enums.RCodeEnum;
import com.hxzy.common.resp.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * springmvc全局异常处理
 *
 * @author tonneyyy
 */
@Log4j2
@RestControllerAdvice
public class GlobalExceptionHandler {




    /**
     * 获取 hibernate-validator异常的
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidationExceptions(MethodArgumentNotValidException ex) {
        //记录日志
        log.error(ex);

        BindingResult result = ex.getBindingResult();
        //错误
        String msg= result.getAllErrors().get(0).getDefaultMessage();

        return R.fail(RCodeEnum.PARAMETERS_ERROR, msg);
    }


    /**
     * sa-token未登录
     * @param e
     * @return
     */
    @ExceptionHandler(NotLoginException.class)
    public R notLoginException(NotLoginException e){
        log.error(e);
        return  R.fail(RCodeEnum.TOKEN_EXPIRED);
    }
    /**
     * 所有异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R handleAllExceptions(Exception ex) {
        //记录日志
        log.error(ex);
       return R.fail(RCodeEnum.PARAMETERS_ERROR, ex.getMessage());
    }
}